package com.ybt.heartratem.moudle;

import static java.lang.Thread.sleep;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Size;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.caysn.autoreplyprint.AutoReplyPrint;
import com.google.common.util.concurrent.ListenableFuture;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import com.ybt.heartratem.R;
import com.ybt.heartratem.common.app.AppController;
import com.ybt.heartratem.common.app.AppViewModelFactory;
import com.ybt.heartratem.common.app.CacheManager;
import com.ybt.heartratem.common.app.Injection;
import com.ybt.heartratem.common.app.MyApplication;
import com.ybt.heartratem.common.entity.ClassInfo;
import com.ybt.heartratem.common.entity.CookBookInfo;
import com.ybt.heartratem.common.entity.RecordData;
import com.ybt.heartratem.common.utils.PrintBitmapUtilsV2;
import com.ybt.heartratem.common.utils.ThreadManager;
import com.ybt.heartratem.common.view.CustomSpinnerAdapter;
import com.ybt.heartratem.common.view.OperateSignNameDialog;
import com.ybt.heartratem.databinding.ActivityMainBinding;
import com.ybt.heartratem.logic.data.http.service.entry.AASRequestBody;
import com.ybt.heartratem.logic.data.listener.OnRefreshListener;
import com.ybt.heartratem.moudle.main.SettingActivity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.MySystemTipsDialog;
import me.goldze.mvvmhabit.http.DownLoadManager;
import me.goldze.mvvmhabit.http.download.ProgressCallBack;
import me.goldze.mvvmhabit.utils.JsonEasy;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastStatusUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.constant.Contact;
import me.tatarka.bindingcollectionadapter2.BR;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import z.hol.shellandroid.ShellAndroid;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainVM>
        implements Handler.Callback, OnRefreshListener {
    public Handler mHandler;
    //public static FreshGoodsManager mFreshGoodsManager;
    public SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
    public SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
    private static String appKey = "9acbd7f0715d40a5959f19a51621d562";
    private static String secretKey = " 9d9928b11ac74eb099c8457b065bfae3";
    private static String serviceKey = "4c495ca26fb2efb21e3b90edf299e7ed";
    private static String companyId = "v21uDmXV+2Ee11/GP1NdWA==";

    // 多媒体相关业务
    private Preview mPreview;
    private ImageCapture imageCapture;
    private ProcessCameraProvider mProcessCameraProvider;
    public String currFilePath;
    //打印机服务
    private List<CookBookInfo> cookBookInfos = new ArrayList<>();
    private String takeWeight;//当前重量
    //留样实体
    private AASRequestBody body = new AASRequestBody();
    private String pic1;
    private String pic2;
    private String pic3;
    private String pic4;
    //餐点类型
    List<String> typeCanList = new ArrayList<>();
    AASRequestBody.Detail detail1 = null;
    AASRequestBody.Detail detail2 = null;
    AASRequestBody.Detail detail3 = null;
    AASRequestBody.Detail detail4 = null;

    @Override
    public MainVM initViewModel() {
        AppController.getInstance().regOnRefreshListener(this);
        AppViewModelFactory factory = AppViewModelFactory.getInstance(MyApplication.getInstance());
        return ViewModelProviders.of(this, factory).get(MainVM.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.loadClassData();
        //intPicAiScan();//图片识别SDK初始化
        mHandler = new Handler(this);
        typeCanList.add("早餐");
        typeCanList.add("午餐");
        typeCanList.add("早点");
        typeCanList.add("下午点");
        typeCanList.add("晚餐");
    }

    //图片识别SDK初始化

    /**
     * private void intPicAiScan() {
     * mFreshGoodsManager = new FreshGoodsManager(this);
     * String workPath = Environment.getExternalStorageDirectory() + "/AiModule";
     * File folder = new File(workPath);
     * if (!folder.exists()) {
     * folder.mkdir();
     * }
     * JSONObject keyInfo = new JSONObject();
     * String companyID = "";
     * try {
     * //购买之后可以获取到companyID、appKey、secretKey、serviceKey，用以激活sdk
     * keyInfo.put("appKey", appKey);
     * keyInfo.put("secretKey", secretKey);
     * keyInfo.put("serviceKey", serviceKey);
     * //1是试用模式（只能识别10个商品）
     * int resultCode = mFreshGoodsManager.RetailBot_Api_ModelInit(companyId, keyInfo.toString(), workPath, 1);
     * KLog.e("菜品识别SDK初始化结果：" + resultCode); //resultCode 0 代表初始化完成
     * } catch (JSONException e) {
     * e.printStackTrace();
     * }
     * }
     **/

    @Override
    protected void onResume() {
        super.onResume();
        getSoftVersion();
        if (MyApplication.teacher == null) {
            MySystemTipsDialog dialog = new MySystemTipsDialog(this);
            dialog.setItem("温馨提示", "请设置当前PAD设备厨师使用人再进行相关业务操作", () -> {
                startActivity(SettingActivity.class);
                dialog.dismiss();
            });
            dialog.setCancelable(false);
            dialog.show();
        }
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        initView();
        PrintFoodTicket();
        initMediaEvent();
    }

    private void initView() {
        binding.schoolNameTv.setText(Injection.aasDataRe().getToken() + "分餐智能终端");
        setData();
        //设置按钮
        binding.settingIv.setOnClickListener(view -> {
            startActivity(SettingActivity.class);
        });

        viewModel.getSaveLiuyangResultEvent.observe(this, flag -> {
            if (flag) {
                detail1 = null;
                detail2 = null;
                detail3 = null;
                detail4 = null;
                if (body.getDetailList() != null && body.getDetailList().size() == 1) {
                    detail1 = body.getDetailList().get(0);
                }
                if (body.getDetailList() != null && body.getDetailList().size() == 2) {
                    detail1 = body.getDetailList().get(0);
                    detail2 = body.getDetailList().get(1);
                }
                if (body.getDetailList() != null && body.getDetailList().size() == 3) {
                    detail1 = body.getDetailList().get(0);
                    detail2 = body.getDetailList().get(1);
                    detail3 = body.getDetailList().get(2);
                }
                if (body.getDetailList() != null && body.getDetailList().size() == 4) {
                    detail1 = body.getDetailList().get(0);
                    detail2 = body.getDetailList().get(1);
                    detail3 = body.getDetailList().get(2);
                    detail4 = body.getDetailList().get(3);
                }
                if (h == null) {
                    ToastStatusUtils.show("打印机未链接", R.drawable.ic_error);
                    return;
                }
                //打印
                new Thread(() -> {
                    try {
                        if (detail1 != null && detail1.getInt1() >0) {
                            Test_Label_SampleTicket_58MM_1(h, detail1);
                        }
                        sleep(3000);
                        if (detail2 != null&& detail2.getInt1() >0) {
                            Test_Label_SampleTicket_58MM_1(h, detail2);
                        }
                        sleep(3000);
                        if (detail3 != null&& detail3.getInt1() >0) {
                            Test_Label_SampleTicket_58MM_1(h, detail3);
                        }
                        sleep(3000);
                        if (detail4 != null&& detail4.getInt1() >0) {
                            Test_Label_SampleTicket_58MM_1(h, detail4);
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
            }
        });
    }

    //加载数据
    public void setData() {
        binding.liuStartDayTv.setText(dayFormat.format(new Date()));
        viewModel.getCookBookEvent.observe(this, list -> {
            if (list != null && !list.isEmpty()) {
                cookBookInfos = list;
                getCanDianResult(typeCanList, binding.jcCdTypeSp.getSelectedItemPosition());
            }
        });

        //班级
        viewModel.getClaInfoListEvent.observe(this, list -> {
            List<String> typeList = new ArrayList<>();
            for (ClassInfo info : list) {
                typeList.add(info.getName());
            }
            CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, R.layout.item_textv_layout, typeList);
            binding.jcClassSp.setAdapter(adapter);
            binding.jcClassSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    TextView tv = (TextView) view;
                    if (tv != null) {
                        tv.setTextSize(26f);
                        tv.setTextColor(getResources().getColor(R.color.login_text_hint_color));
                        //获取餐谱(学生)
                        viewModel.getFoodList("1", binding.liuStartDayTv.getText().toString(),
                                binding.liuStartDayTv.getText().toString());
                        //TODO 班级ID
                        body.setClassID(list.get(pos).getClassID());
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        });


        CustomSpinnerAdapter adapterCan = new CustomSpinnerAdapter(this, R.layout.item_textv_layout, typeCanList);
        binding.jcCdTypeSp.setAdapter(adapterCan);
        binding.jcCdTypeSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                TextView tv = (TextView) view;
                if (tv != null) {
                    tv.setTextSize(24f);
                    tv.setTextColor(getResources().getColor(R.color.login_text_hint_color));
                    //TODO 餐食类型
                    body.setText2(typeCanList.get(pos));
                    getCanDianResult(typeCanList, pos);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //留样日期
        binding.liuStartDayTv.setOnClickListener(view1 -> {
            Calendar mcalendar = Calendar.getInstance();
            int year = mcalendar.get(Calendar.YEAR);
            int month = mcalendar.get(Calendar.MONTH);
            final int day = mcalendar.get(Calendar.DAY_OF_MONTH);
            new DatePickerDialog(this, (view, year12, month12, dayOfMonth) -> {
                binding.liuStartDayTv.setText(year12 + "-" + ((month12 + 1) < 10 ? ("0" + (month12 + 1)) : (month12 + 1)) + "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth));
                //获取餐谱
                viewModel.getFoodList( "1", binding.liuStartDayTv.getText().toString(),binding.liuStartDayTv.getText().toString());
            }, year, month, day).show();
        });
        //留样时间
        /**binding.liuStartTimeTv.setOnClickListener(view1 -> {
         Calendar calendar = Calendar.getInstance();
         int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
         int minute = calendar.get(Calendar.MINUTE);
         new TimePickerDialog(this, (view, hourOfDay12, minute12) -> {
         if ("请选择".equals(binding.liuStartDayTv.getText().toString())) {
         ToastUtils.showLong("请选择留样日期");
         return;
         }
         binding.liuStartTimeTv.setText("" + (hourOfDay12 < 10 ? ("0" + hourOfDay12) : hourOfDay12)
         + ":" + (minute12 < 10 ? ("0" + minute12) : minute12));
         //TODO 留样时间
         body.setDate1(binding.liuStartDayTv.getText().toString() + " " + binding.liuStartTimeTv.getText().toString());
         }, hourOfDay, minute, true).show();
         });**/

        //留样人签名
        binding.signLyPersonNameTv.setOnClickListener(view1 -> {
            OperateSignNameDialog dialog = new OperateSignNameDialog(this);
            dialog.setItem(key -> {
                Glide.with(this).load(new File(key)).into(binding.signLyPersonNameIv);
                body.setText7(Contact.getimage(key));//TODO 留样人签名
            });
            dialog.show();
        });

        binding.take1Tv.setOnClickListener(view -> {
            String temp = Injection.aasDataRe().getConfigInfo();
            int weight = 0;
            if (!TextUtils.isEmpty(temp)) {
                weight = Integer.parseInt(temp);
            }
            if (TextUtils.isEmpty(takeWeight)) {
                ToastUtils.showLong("获取重量异常");
                return;
            }
            binding.foodWeight1Tv.setText(String.valueOf(Double.parseDouble(takeWeight) - weight));
            takePhoto(binding.foodPic1Iv, pic1);
            pic1 = currFilePath;
        });
        binding.take2Tv.setOnClickListener(view -> {
            String temp = Injection.aasDataRe().getConfigInfo();
            int weight = 0;
            if (!TextUtils.isEmpty(temp)) {
                weight = Integer.parseInt(temp);
            }
            if (TextUtils.isEmpty(takeWeight)) {
                ToastUtils.showLong("获取重量异常");
                return;
            }
            binding.foodWeight2Tv.setText(String.valueOf(Double.parseDouble(takeWeight) - weight));
            takePhoto(binding.foodPic2Iv, pic2);
            pic2 = currFilePath;
        });
        binding.take3Tv.setOnClickListener(view -> {
            String temp = Injection.aasDataRe().getConfigInfo();
            int weight = 0;
            if (!TextUtils.isEmpty(temp)) {
                weight = Integer.parseInt(temp);
            }
            if (TextUtils.isEmpty(takeWeight)) {
                ToastUtils.showLong("获取重量异常");
                return;
            }
            binding.foodWeight3Tv.setText(String.valueOf(Double.parseDouble(takeWeight) - weight));
            takePhoto(binding.foodPic3Iv, pic3);
            pic3 = currFilePath;
        });
        binding.take4Tv.setOnClickListener(view -> {
            String temp = Injection.aasDataRe().getConfigInfo();
            int weight = 0;
            if (!TextUtils.isEmpty(temp)) {
                weight = Integer.parseInt(temp);
            }
            if (TextUtils.isEmpty(takeWeight)) {
                ToastUtils.showLong("获取重量异常");
                return;
            }
            binding.foodWeight4Tv.setText(String.valueOf(Double.parseDouble(takeWeight) - weight));
            takePhoto(binding.foodPic4Iv, pic4);
            pic4 = currFilePath;
        });


        //保存及打印
        binding.commitTv.setOnClickListener(view -> {
            /**if (TextUtils.isEmpty(binding.bingxiangWenduEdt.getText().toString())) {
             ToastUtils.showLong("请输入冰箱温度");
             return;
             }**/
            body.setSchoolID(Integer.parseInt(Injection.aasDataRe().getUserName()));//学校
            body.setCreateUserID(MyApplication.teacher.getUserID());//创建人ID
            body.setText3(MyApplication.teacher.getName());//留样人姓名
            body.setModelType(2001);//模块编码
            //温度
            //body.setInt2(Integer.parseInt(binding.bingxiangWenduEdt.getText().toString()));
            //留样的总总量
            int food1 = 0;
            if (!TextUtils.isEmpty(binding.foodWeight1Tv.getText())) {
                food1 = (int) Double.parseDouble(binding.foodWeight1Tv.getText().toString());
            }
            int food2 = 0;
            if (!TextUtils.isEmpty(binding.foodWeight2Tv.getText())) {
                food2 = (int) Double.parseDouble(binding.foodWeight2Tv.getText().toString());
            }
            int food3 = 0;
            if (!TextUtils.isEmpty(binding.foodWeight3Tv.getText())) {
                food3 = (int) Double.parseDouble(binding.foodWeight3Tv.getText().toString());
            }
            int food4 = 0;
            if (!TextUtils.isEmpty(binding.foodWeight4Tv.getText())) {
                food4 = (int) Double.parseDouble(binding.foodWeight4Tv.getText().toString());
            }
            body.setInt2(food1 + food2 + food3 + food4);
            List<AASRequestBody.Detail> detailList = new ArrayList<>();
            if (!TextUtils.isEmpty(binding.lyFoodName1Edt.getText())) {
                AASRequestBody.Detail detail1 = new AASRequestBody.Detail();
                detail1.setText1(binding.lyFoodName1Edt.getText().toString());//留样食品名称
                detail1.setText3(Contact.getimage(pic1));//留样食品照片
                detail1.setInt1(food1);//留样1重量
                detailList.add(detail1);
            }
            if (!TextUtils.isEmpty(binding.lyFoodName2Edt.getText())) {
                AASRequestBody.Detail detail2 = new AASRequestBody.Detail();
                detail2.setText1(binding.lyFoodName2Edt.getText().toString());//留样食品名称
                detail2.setText3(Contact.getimage(pic2));//留样食品照片
                detail2.setInt1(food2);//留样1重量
                detailList.add(detail2);
            }

            if (!TextUtils.isEmpty(binding.lyFoodName3Edt.getText())) {
                AASRequestBody.Detail detail3 = new AASRequestBody.Detail();
                detail3.setText1(binding.lyFoodName3Edt.getText().toString());//留样食品名称
                detail3.setText3(Contact.getimage(pic3));//留样食品照片
                detail3.setInt1(food3);//留样1重量
                detailList.add(detail3);
            }
            if (!TextUtils.isEmpty(binding.lyFoodName4Edt.getText())) {
                AASRequestBody.Detail detail4 = new AASRequestBody.Detail();
                detail4.setText1(binding.lyFoodName4Edt.getText().toString());//留样食品名称
                detail4.setText3(Contact.getimage(pic4));//留样食品照片
                detail4.setInt1(food4);//留样1重量
                detailList.add(detail4);
            }
            body.setDetailList(detailList);
            viewModel.reqBody.set(body);
            viewModel.addRecord();
        });
    }

    /***
     * 视频图片初始化
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint({"RestrictedApi", "WrongConstant"})
    private void initMediaEvent() {
        AppController.mMainHandler.post(() -> {
            ListenableFuture<ProcessCameraProvider> listenableFuture = ProcessCameraProvider.getInstance(this);
            try {
                mProcessCameraProvider = listenableFuture.get();
                mPreview = new Preview.Builder()
                        .setTargetResolution(new Size(640, 480))
                        .build();
                mPreview.setSurfaceProvider(binding.previewActivityVideoRecode.createSurfaceProvider());
                ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                        .build();
                imageAnalysis
                        .setAnalyzer(ContextCompat.getMainExecutor(this),
                                image -> {
                                    image.close();
                                }
                        );
                mProcessCameraProvider.bindToLifecycle((LifecycleOwner) this, CameraSelector.DEFAULT_BACK_CAMERA,
                        mPreview, imageAnalysis);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void getCanDianResult(List<String> typeCanList, int pos) {
        if (cookBookInfos != null && !cookBookInfos.isEmpty()) {
            if ("早餐".equals(typeCanList.get(pos))) {
                binding.lyFoodName1Edt.setText(null);
                binding.lyFoodName2Edt.setText(null);
                binding.lyFoodName3Edt.setText(null);
                binding.lyFoodName4Edt.setText(null);
                if (!TextUtils.isEmpty(cookBookInfos.get(0).getZaoCan())) {
                    //TODO 餐食名称
                    body.setText1(cookBookInfos.get(0).getZaoCan());
                    String separators = ",;，；|-";
                    String[] parts = cookBookInfos.get(0).getZaoCan().split("[" + separators + "]+");
                    if (parts.length == 1) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                    }
                    if (parts.length == 2) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                    }
                    if (parts.length == 3) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                    }
                    if (parts.length >= 4) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                        binding.lyFoodName4Edt.setText(parts[3]);
                    }
                }
            } else if ("午餐".equals(typeCanList.get(pos))) {
                binding.lyFoodName1Edt.setText(null);
                binding.lyFoodName2Edt.setText(null);
                binding.lyFoodName3Edt.setText(null);
                binding.lyFoodName4Edt.setText(null);
                if (!TextUtils.isEmpty(cookBookInfos.get(0).getWuCan())) {
                    //TODO 餐食名称
                    body.setText1(cookBookInfos.get(0).getWuCan());
                    String separators = ",;，；|-";
                    String[] parts = cookBookInfos.get(0).getZaoCan().split("[" + separators + "]+");
                    if (parts.length == 1) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                    }
                    if (parts.length == 2) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                    }
                    if (parts.length == 3) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                    }
                    if (parts.length >= 4) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                        binding.lyFoodName4Edt.setText(parts[3]);
                    }
                }
            } else if ("早点".equals(typeCanList.get(pos))) {
                binding.lyFoodName1Edt.setText(null);
                binding.lyFoodName2Edt.setText(null);
                binding.lyFoodName3Edt.setText(null);
                binding.lyFoodName4Edt.setText(null);
                if (!TextUtils.isEmpty(cookBookInfos.get(0).getZaoDian())) {
                    //TODO 餐食名称
                    body.setText1(cookBookInfos.get(0).getZaoDian());
                    String separators = ",;，；|-";
                    String[] parts = cookBookInfos.get(0).getZaoDian().split("[" + separators + "]+");
                    if (parts.length == 1) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                    }
                    if (parts.length == 2) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                    }
                    if (parts.length == 3) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                    }
                    if (parts.length >= 4) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                        binding.lyFoodName4Edt.setText(parts[3]);
                    }
                }
            } else if ("下午点".equals(typeCanList.get(pos))) {
                binding.lyFoodName1Edt.setText(null);
                binding.lyFoodName2Edt.setText(null);
                binding.lyFoodName3Edt.setText(null);
                binding.lyFoodName4Edt.setText(null);
                if (!TextUtils.isEmpty(cookBookInfos.get(0).getXiaWuDian())) {
                    //TODO 餐食名称
                    body.setText1(cookBookInfos.get(0).getXiaWuDian());
                    String separators = ",;，；|-";
                    String[] parts = cookBookInfos.get(0).getXiaWuDian().split("[" + separators + "]+");
                    if (parts.length == 1) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                    }
                    if (parts.length == 2) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                    }
                    if (parts.length == 3) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                    }
                    if (parts.length >= 4) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                        binding.lyFoodName4Edt.setText(parts[3]);
                    }
                }
            } else if ("晚餐".equals(typeCanList.get(pos))) {
                binding.lyFoodName1Edt.setText(null);
                binding.lyFoodName2Edt.setText(null);
                binding.lyFoodName3Edt.setText(null);
                binding.lyFoodName4Edt.setText(null);
                if (!TextUtils.isEmpty(cookBookInfos.get(0).getWuCan())) {
                    //TODO 餐食名称
                    body.setText1(cookBookInfos.get(0).getWuCan());
                    String separators = ",;，；|-";
                    String[] parts = cookBookInfos.get(0).getWuCan().split("[" + separators + "]+");
                    if (parts.length == 1) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                    }
                    if (parts.length == 2) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                    }
                    if (parts.length == 3) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                    }
                    if (parts.length >= 4) {
                        binding.lyFoodName1Edt.setText(parts[0]);
                        binding.lyFoodName2Edt.setText(parts[1]);
                        binding.lyFoodName3Edt.setText(parts[2]);
                        binding.lyFoodName4Edt.setText(parts[3]);
                    }
                }
            }
        }
    }

    @SuppressLint("RestrictedApi")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void takePhoto(ImageView targetIv, String pic) {
        imageCapture = new ImageCapture.Builder()
                //优化捕获速度，可能降低图片质量
                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                //设置宽高比
                .setTargetResolution(new Size(640, 480))
                //设置初始的旋转角度
                .build();

        mPreview = new Preview.Builder()
                .setTargetResolution(new Size(640, 480))
                .build();
        mPreview.setSurfaceProvider(binding.previewActivityVideoRecode.createSurfaceProvider());

        String dirPath = CacheManager.SD_IMAGE_DIR + File.separator + "SpaceRecode";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            boolean mkdir = dirFile.mkdir();
        }
        File file = new File(dirFile, System.currentTimeMillis() + ".jpg");
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mProcessCameraProvider.unbindAll();
        ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(file).build();
        mProcessCameraProvider.bindToLifecycle((LifecycleOwner) this, CameraSelector.DEFAULT_BACK_CAMERA,
                mPreview, imageCapture
        );
        AppController.mMainHandler.postDelayed(() -> {
            imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
                @Override
                public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                    Uri savedUri = outputFileResults.getSavedUri();
                    if (savedUri == null) {
                        Uri.fromFile(file);
                    }
                    Glide.with(MainActivity.this).load(file).into(targetIv);
                    currFilePath = file.getPath();
                    KLog.e("餐食照片：" + currFilePath);
                    /**
                     * 实际使用中要使用拍摄的bitmap,这里是例子，没有进行拍摄，该对象为null，使用时会出错
                     * Bitmap bitmap = ImageUtils.getBitmap(MainActivity.this, currFilePath);
                     StringBuffer sid = new StringBuffer();
                     StringBuffer result = new StringBuffer(1024);
                     int ret = mFreshGoodsManager.RetailBot_Api_Recognition(sid, result, bitmap);
                     JSONArray totalArray = null;//数组索引1及以后的时识别的结果
                     try {
                     totalArray = new JSONArray(result.toString());
                     String sidReturn = (String) totalArray.get(0); //或者String sidReturn = sid.toString();
                     KLog.e("菜品识别结果：" + sidReturn);
                     //TODO 使用识别结果
                     //["20191116155718582894697",  //session_id
                     //["800116",    0.325056], //商品ID，置信度
                     //["800115",    0.0590677],

                     } catch (JSONException e) {
                     throw new RuntimeException(e);
                     }**/
                }

                @Override
                public void onError(@NonNull ImageCaptureException exception) {
                    KLog.e(TAG, "onError: " + exception);
                }
            });
        }, 200);
    }


    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {

        }
        return false;
    }

    private void getSoftVersion() {
        try {
            String url = "http://api.sztbhz.com/newSchoolOAMobileService/LiuYang—PadAI-Version.txt";
            Request request = new Request.Builder().url(url).get().build();
            OkHttpClient okHttpClient = new OkHttpClient();
            final okhttp3.Call call = okHttpClient.newCall(request);
            ThreadManager.getNormalPool().execute(() -> {
                try {
                    okhttp3.Response response = call.execute();
                    String responseResult = response.body().string().replaceAll("\\n|\\s*", "");
                    if (TextUtils.isEmpty(responseResult)) {
                        return;
                    }
                    KLog.e("版本检查返回：" + responseResult);
                    String resultVersion = JsonEasy.getString(responseResult, "version");
                    if (TextUtils.isEmpty(resultVersion)) {
                        return;
                    }
                    int version = Integer.parseInt(resultVersion);
                    String versionUrl = JsonEasy.getString(responseResult, "url");
                    if (version > Contact.getVersionCode()) {
                        DownLoadManager.getInstance().load(versionUrl, new ProgressCallBack(CacheManager.SD_APK_DIR, "LiuYang—PadAI-Version.apk") {
                            @Override
                            public void onSuccess(Object o) {
                                File file = new File(CacheManager.SD_APK_DIR + File.separator + "LiuYang—PadAI-Version.apk");
                                ShellAndroid mShell = new ShellAndroid(null);
                                String flagFile = mShell.initFlagMinimum(mContext);
                                mShell.printOutput();
                                mShell.setFlagFile(flagFile);
                                mShell.checkRoot();
                                mShell.exec(true, "pm install -r " + file.getAbsolutePath());
                                KLog.e("ApkInstall", "执行安装文件：" + file.getAbsolutePath());
                            }

                            @Override
                            public void progress(long progress, long total) {
                            }

                            @Override
                            public void onError(Throwable e) {

                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProcessCameraProvider != null) {
            mProcessCameraProvider.unbindAll();
            mProcessCameraProvider.shutdown();
        }
        if (mPreview != null) {
            mPreview.onDestroy();
        }
        if (h != null) {
            AutoReplyPrint.INSTANCE.CP_Port_Close(h);
        }
    }

    @Override
    public void onRefresh(String weight) {
        takeWeight = weight;
    }


    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        // 缩放图片的尺寸
        float scaleWidth = (float) w / bitmapWidth;
        float scaleHeight = (float) h / bitmapHeight;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
    }

    public static Bitmap resizeImageToWidth(Bitmap bitmap, int w) {
        int h = w * bitmap.getHeight() / bitmap.getWidth();
        return resizeImage(bitmap, w, h);
    }

    // 获取打印机设备
    private UsbDevice GetPrinterUsbDevice() {
        UsbManager usbManager = (UsbManager) getSystemService(USB_SERVICE);
        HashMap<String, UsbDevice> deviceHashMap = usbManager.getDeviceList();
        Collection<UsbDevice> deviceCollection = deviceHashMap.values();
        for (UsbDevice usbDevice : deviceCollection) {
            // 检查是否是我们的打印机
            if ((usbDevice.getVendorId() == 0x4b43)) {
                return usbDevice;
            }
        }
        return null;
    }

    // 检查是否有权限，如果没有权限，申请权限
    // 这一步一定要做，如果没有权限，所有的USB读写操作都是不被允许的
    // 而且每次设备USB数据线断开重连之后，都要重新申请权限
    // 具体的请看UsbManager的requestPermission函数就可以知道了
    private boolean CheckUsbDevicePermission(UsbDevice usbDevice) {
        UsbManager usbManager = (UsbManager) getSystemService(USB_SERVICE);
        if (usbManager.hasPermission(usbDevice)) {
            return true;
        } else {
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(getPackageName()), 0);
            usbManager.requestPermission(usbDevice, pendingIntent);
            return false;
        }
    }

    // 打开设备
    private Pointer OpenUsbDevice(UsbDevice usbDevice) {
        Pointer h = Pointer.NULL;
        if (usbDevice != null) {
            //String usbPort = String.format("VID:0x%04X,PID:0x%04X", usbDevice.getVendorId(), usbDevice.getProductId());
            String usbPort = "VID:0x4b43,PID:0x3538";
            h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb(usbPort, 0);
        }
        KLog.e(TAG, h == Pointer.NULL ? "OpenPort Failed" : "OpenPort Success");
        if (h == Pointer.NULL) {
            ToastUtils.showLong("OpenPort Failed");
        }
        return h;
    }

    /***
     * 打印标签食品信息
     */
    public Pointer h;

    private void PrintFoodTicket() {
        UsbDevice usbDevice = GetPrinterUsbDevice();
        if (usbDevice == null) {
            ToastUtils.showLong("Not Found Usb Printer");
            return;
        }
        if (!CheckUsbDevicePermission(usbDevice)) {
            ToastUtils.showLong("Not Usb Permission");
            return;
        }
        h = OpenUsbDevice(usbDevice);
        if (h != Pointer.NULL) {
            ToastUtils.showLong("USB Pointer Success");
        } else {
            ToastUtils.showLong("Not Usb Pointer");
        }
    }

    private void Test_Label_SampleTicket_58MM_1(Pointer h, AASRequestBody.Detail detail) {
        KLog.e("开始打印");
        AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteMode(h);
        AutoReplyPrint.INSTANCE.CP_Pos_SetMultiByteEncoding(h, AutoReplyPrint.CP_MultiByteEncoding_UTF8);
        AutoReplyPrint.INSTANCE.CP_Label_PageBegin(h, 0, 0, 400, 300, 0);
        AutoReplyPrint.INSTANCE.CP_Label_DrawText(h, 20, 15, 24, 0, "食品：" + detail.getText1());
        AutoReplyPrint.INSTANCE.CP_Label_DrawText(h, 20, 60, 24, 0, "重量：" + detail.getInt1() + "克");
        AutoReplyPrint.INSTANCE.CP_Label_DrawText(h, 20, 94, 24, 0, "留样人：" + body.getText3());
        /**AutoReplyPrint.INSTANCE.CP_Label_DrawBarcode(h, 20, 94,
         AutoReplyPrint.CP_Label_BarcodeType_CODE128,
         AutoReplyPrint.CP_Label_BarcodeTextPrintPosition_BelowBarcode,
         60, 2, 0, "留样人：" + body.getText3());**/

        AutoReplyPrint.INSTANCE.CP_Label_DrawText(h, 20, 130, 24, 0, "留样时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        AutoReplyPrint.INSTANCE.CP_Label_PagePrint(h, 1);
        Test_Pos_QueryPrintResult(h);
    }

    private void Test_Pos_QueryPrintResult(Pointer h) {
        boolean result = AutoReplyPrint.INSTANCE.CP_Pos_QueryPrintResult(h, 3000);
        if (!result) {
            KLog.e("Print failed");
        } else {
            KLog.e("Print Success");
        }
    }
}